import { NoticeService } from './../../providers/notice-service';
import { Component, Input, ViewChild, Output, EventEmitter, Renderer } from '@angular/core';
import { NativeAudio } from "@ionic-native/native-audio";
import { emoarr1 } from '../../global/lib';

@Component({
  selector: 'app-txtView',
  templateUrl: 'app-txtView.html'
})
export class AppTxtViewComponent {
  isExpres: boolean = false;
  str = "";
  isTxtNull;
  _inputTxt;

  emoarrList = [];

  private lastEditRange;
  private _onChange = (value) => { }

  @ViewChild('input') input;

  @Output('focus') focus = new EventEmitter();

  @Input()
  get inputTxt() {
    return this._inputTxt
  }
  set inputTxt(val: any) {
    this._inputTxt = val
  }

  constructor(public nativeAudio: NativeAudio,
    private renderer: Renderer,
    public noticeService: NoticeService
  ) {

  }
  /**
   * 对讲
   */
  Intercom() {
    this.slides = false;
    //关闭键盘

    this.noticeService.showNoticeByToast(1, "对讲");
  }


  slides = false;
  expreshow = false;
  /**
   * 表情
   */
  Expression() {
    this.isChoice = false;
    this.isExpres = true;
    this.slides = true;

    this.noticeService.showNoticeByToast(1, "表情");
    this.emoarrFn();
  }

  isChoice = false;
  /**
   * 选择则
   */
  Choice() {
    this.isExpres = false;
    this.isChoice = true;
    this.slides = true;
    this.noticeService.showNoticeByToast(1, "选择则");
  }
  /**
   * 发送
   */
  SendOut() {
    //console.log(this.str);
    let str = this.str;
    this.str = "";
    this.noticeService.showNoticeByToast(1, str);
  }

  emoarrFn() {
    let ss = emoarr1;
    this.emoarrList = [];
    for (let Key in ss) {
      this.emoarrList.push(ss[Key]);
    }
  }
  /**
   * 插入表情
   * @param emo 表情
   */
  emoarrClisk(emo) {
    //console.log(event);
    this.insertImg(emo);

  }

  writeValue(value: any): void {
    this.renderer.setElementProperty(this.input.nativeElement, 'innerHTML', value);
  }

  registerOnChange(fn: any): void {
    this._onChange = fn;
  }

  registerOnTouched(fn: any): void {
  }
  /**
   * input 点击事件
   */
  public saveLastEditRange() {
    try {
      // 获取选定对象
      let selection = getSelection();
      // 设置最后光标对象
      this.lastEditRange = selection.getRangeAt(0);
    } catch (e) {
      //console.log(e);
    }

  }
  /**
   *  按键  事件放开
   * @param e 
   */
  onKeypress(e) {
    if (e.keyCode == 13) {
      e.preventDefault();

      let event = new Event('submit');
      event.initEvent('submit', true, true);
      document.forms[0].dispatchEvent(event);
    }

  }

  onInput(e) {
    this._onChange(e.target.innerHTML);
  }

  insertImg(src) {
    // 获取编辑框对象
    let inputEl = this.input.nativeElement;
    //表情图片
    // let img=src;
    let img = new Image();
    img.src = src;
    img.style.width = "1.7em";
    img.style.height = "1.7em";
    let range = this.lastEditRange;

    // 判断是否有最后光标对象存在
    if (!range) {
      range = document.createRange();
      range.setStart(inputEl, 0);
    }

    // 判断选定对象范围是编辑框还是文本节点
    if (range.startContainer.nodeName != '#text') {
      let childNodes = inputEl.childNodes;
      let anchorOffset = range.startOffset;
      let extentOffset = range.endOffset;

      //移除选中部分
      for (let i = anchorOffset; i < extentOffset; i++) {
        inputEl.removeChild(childNodes[i]);
        i--;
        extentOffset--;
      }

      // 如果文本框的子元素大于0，则表示有其他元素，则按照位置插入表情节点
      if (inputEl.childNodes.length > 0 && childNodes.length > anchorOffset) {

        for (let i = 0; i < childNodes.length; i++) {
          if (i == anchorOffset) {
            inputEl.insertBefore(img, childNodes[i]);
            break;
          }

        }
      } else {
        // 否则直接插入一个表情元素
        inputEl.appendChild(img);
      }
      // 创建新的光标对象
      range = document.createRange();
      // 光标位置定位在表情节点的最大长度
      range.setStart(inputEl, anchorOffset + 1);

    } else {
      // 获取光标对象的范围界定对象，一般就是textNode对象
      let textNode = <Text>range.startContainer;
      // 获取光标位置
      let rangeStartOffset = range.startOffset;
      //删除选择内容
      textNode.deleteData(rangeStartOffset, range.endOffset - rangeStartOffset);
      //分割文本节点
      let textNodeSplited = textNode.splitText(rangeStartOffset);
      //插入图片
      textNodeSplited.parentElement.insertBefore(img, textNodeSplited);

      // 光标移动到到原来的位置加上新内容的长度
      range.setStart(textNodeSplited, 0);
    }
    // 无论如何都要记录最后光标对象
    this.lastEditRange = range;

    this._onChange(inputEl.innerHTML);


  }

}
